package com.tangkeyon.service.impl;

import com.alipay.api.AlipayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.config.Configs;
import com.alipay.demo.trade.model.ExtendParams;
import com.alipay.demo.trade.model.GoodsDetail;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.alipay.demo.trade.service.impl.AlipayTradeServiceImpl;
import com.alipay.demo.trade.utils.ZxingUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tangkeyon.common.Const;
import com.tangkeyon.common.ResponseCode;
import com.tangkeyon.dao.*;
import com.tangkeyon.pojo.*;
import com.tangkeyon.service.IOrderService;
import com.tangkeyon.util.BigDecimalUtil;
import com.tangkeyon.util.DateTimeUtil;
import com.tangkeyon.util.FTPUtils;
import com.tangkeyon.util.PropertiesUtil;
import com.tangkeyon.vo.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Author: tangkeyon@gmail.com
 * @Date: 2019/6/14 19:18
 * @Version 1.0
 */
@Service("iOrderService")
public class IOrderServiceImpl implements IOrderService {

    private static AlipayTradeService tradeService;
    static  {

        /** 一定要在创建AlipayTradeService之前调用Configs.init()设置默认参数
         *  Configs会读取classpath下的zfbinfo.properties文件配置信息，如果找不到该文件则确认该文件是否在classpath目录
         */
        Configs.init("zfbinfo.properties");

        /** 使用Configs提供的默认参数
         *  AlipayTradeService可以使用单例或者为静态成员对象，不需要反复new
         */
        tradeService = new AlipayTradeServiceImpl.ClientBuilder().build();
    }
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private PayInfoMapper payInfoMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper  productMapper;
    @Autowired
    private ShippingMapper shippingMapper;

    private static final Logger logger=LoggerFactory.getLogger(IOrderServiceImpl.class);

    @Override
    public ResponseCode create(Integer userId, Integer shippingId){
        //根据用户Id查出购物车中所有已勾选的商品
        List<Cart> cartList = cartMapper.selectCheckProduct(userId);
        ResponseCode responseCode = this.assembleOrderItem(cartList);
        //装配OrderItem成功
        if(responseCode.ifSuccess()){
            List<OrderItem>orderItemList = (List<OrderItem>) responseCode.getData();
            //计算出所有订单项价格的总和
            BigDecimal totalPrice = this.getOrderTotalPrice(orderItemList);
            //装配Order
            Order order = this.assembleOrder(userId, shippingId, totalPrice);

            //为所有的OrderItem设置订单号
            this.addOrderItemOrderNo(orderItemList,order.getOrderNo());
            //数据表添加订单项集合

            orderItemMapper.insertBatch(orderItemList);
            //减少库存
            this.reduceStock(orderItemList);
           //清空购物车
            this.clearShoppingCart(cartList);
           //返回数据给页面
            OrderVo orderVo = this.assembleOrderVO(order, orderItemList);
            if(order !=null){
                return ResponseCode.creatBySuccess(orderVo);
            }
            return ResponseCode.createByErrorMessage("对象装配失败");
        }

        return ResponseCode.createByErrorMessage("对象装配失败");
    }

    @Override
    public ResponseCode cancel(Integer userId, Long orderNo) {
        //判断订单是否存在
        Order order = orderMapper.selectOrderByOrderIdUserId(orderNo, userId);
        if(order!=null){
            //判断是否发货，发货之后无法取消订单
            if(order.getStatus()>Const.OrderStatusEnum.SHIPPED.getCode()){
                return  ResponseCode.createByErrorMessage("订单已经发货，不可取消");
            }
            order.setStatus(Const.OrderStatusEnum.CANCEL.getCode());
            int row = orderMapper.updateByPrimaryKeySelective(order);
            if(row>0){
                return ResponseCode.creatBySuccess("订单取消成功");
            }
                return  ResponseCode.createByErrorMessage("订单取消失败");
        }
        return ResponseCode.createByErrorMessage("订单不存在");
    }

    @Override
    public ResponseCode getOrderCartProduct(Integer userId) {
        //查询用户购物车中选中的商品
        List<Cart> cartList = cartMapper.selectCheckProduct(userId);
        if(CollectionUtils.isNotEmpty(cartList)){
            ResponseCode responseCode = this.assembleOrderItem(cartList);
            if (responseCode.ifSuccess()){
                List<OrderItem> orderItemList = (List<OrderItem>) responseCode.getData();
                List<OrderItemVo> orderItemVoList = this.assembleOrderItemVo(orderItemList);
                OrderProductVO orderProductVO = this.assembleOrderProductVO(orderItemVoList);
                if(orderProductVO !=null){
                    return ResponseCode.creatBySuccess(orderProductVO);
                }
                   return  ResponseCode.createByError();
            }
        }
        return ResponseCode.createByErrorMessage("该用户购物车中未选中商品");
    }

    @Override
    public ResponseCode<OrderVo> detail(Integer userId, Long orderId) {
        Order order = orderMapper.selectOrderByOrderIdUserId(orderId, userId);
        if(order !=null){
            List<OrderItem> orderItemList = orderItemMapper.selectListOrderItem(userId, orderId);
            OrderVo orderVo = this.assembleOrderVO(order, orderItemList);
            return ResponseCode.creatBySuccess(orderVo);
        }
        return ResponseCode.createByErrorMessage("该用户没有此订单");
    }

    @Override
    public ResponseCode<PageInfo> list(Integer userId, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
         if(userId!=null && pageSize!=null && pageNum !=null){
             //根据用户id查出所有的订单
             List<Order> orderList = orderMapper.selectOrderByUserId(userId);
             //获得orderVoList
             List<OrderVo> orderVoList = this.assembleOrderVO(orderList, userId);
             PageInfo pageInfo=new PageInfo(orderVoList);
             return ResponseCode.creatBySuccess(pageInfo);
          }
               return ResponseCode.createByErrorMessage("该用户的订单列表为空");

    }


    @Override
    public ResponseCode manageOrderList(Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        //查询所有订单
        List<Order> orderList = orderMapper.selectOrderByUserId(null);
        if(CollectionUtils.isNotEmpty(orderList)){
            List<OrderVo> orderVoList = this.assembleOrderVO(orderList, null);
            PageInfo pageInfo=new PageInfo(orderVoList);
            return ResponseCode.creatBySuccess(pageInfo);
        }
          return ResponseCode.createByErrorMessage("订单不存在");
    }

    @Override
    public ResponseCode manageDetail(Long orderNo) {
        Order order = orderMapper.selectOrderByOrderNo(orderNo);
        if(order!=null){
            List<OrderItem> orderItemList = orderItemMapper.selectOrderItemByOrderNo(order.getOrderNo());
            OrderVo orderVo = this.assembleOrderVO(order, orderItemList);
            return ResponseCode.creatBySuccess(orderVo);
        }
        return ResponseCode.createByErrorMessage("订单不存在");
    }

    @Override
    public ResponseCode searchOrder(Long orderNo, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        Order order = orderMapper.selectOrderByOrderNo(orderNo);
        if(order!=null){
            List<OrderItem> orderItemList = orderItemMapper.selectOrderItemByOrderNo(order.getOrderNo());
            OrderVo orderVo = this.assembleOrderVO(order, orderItemList);
            PageInfo pageInfo=new PageInfo(Lists.newArrayList(orderVo));

            return ResponseCode.creatBySuccess(pageInfo);

        }
        return ResponseCode.createByErrorMessage("订单不存在");
    }

    @Override
    public ResponseCode<String> orderSendGoods(Long orderNo) {
        Order order = orderMapper.selectOrderByOrderNo(orderNo);
        if(order !=null){
            if(order.getStatus()==Const.OrderStatusEnum.PAYED.getCode()){
                order.setStatus(Const.OrderStatusEnum.SHIPPED.getCode());
                order.setSendTime(new Date());
                int row = orderMapper.insertSelective(order);
                if(row>0){
                    return  ResponseCode.creatBySuccess("发货成功");
                }
                    return ResponseCode.createByErrorMessage("发货失败");
            }
                    return  ResponseCode.createByErrorMessage("商品为付款");
        }

        return ResponseCode.createByErrorMessage("该用户没有以上订单");

    }

    private ResponseCode assembleOrderItem(List<Cart> cartList){

        if(CollectionUtils.isEmpty(cartList)){
            return ResponseCode.createByErrorMessage("购物车中商品为空");
        }

        List<OrderItem> orderItemList=Lists.newArrayList();
        for(Cart cartItem:cartList){
            //对象要放在循环里面创建，每一次循环都是创建出一个新的对象
            OrderItem orderItem=new OrderItem();
            orderItem.setUserId(cartItem.getUserId());
            orderItem.setProductId(cartItem.getProductId());
            Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());
            if(cartItem.getQuantity()>product.getStock()){
                return ResponseCode.createByErrorMessage("该商品库存不足");
            }
             orderItem.setQuantity(cartItem.getQuantity());
            if(product.getStatus()>Const.ProductStatus.ON_SAIL.getCode()){
                return  ResponseCode.createByErrorMessage("该商品已经下架");
            }
            orderItem.setProductName(product.getName());
            orderItem.setProductImage(product.getMainImage());
            orderItem.setCurrentUnitPrice(product.getPrice());
            BigDecimal productTotalPrice=new BigDecimal("0");
            productTotalPrice=BigDecimalUtil.multiply(orderItem.getCurrentUnitPrice().doubleValue(),orderItem.getQuantity().doubleValue());
            orderItem.setTotalPrice(productTotalPrice);
            orderItemList.add(orderItem);
        }
        return ResponseCode.creatBySuccess(orderItemList);
    }

    private Order assembleOrder(Integer userId, Integer shippingId,BigDecimal totalPrice){
            Order order=new Order();
            order.setOrderNo(this.generateOrderNo());
            order.setUserId(userId);
            order.setShippingId(shippingId);
            order.setPaymentType(Integer.valueOf(Const.PaymentTypeEnum.ONLINE_PAY.getCode()));
            order.setPostage(0);
            order.setPayment(totalPrice);
            order.setStatus(Const.OrderStatusEnum.NO_PAY.getCode());
        int resultCount = orderMapper.insert(order);
        if(resultCount>0){
            return order;
        }
        return null;
    }

    private List<OrderVo> assembleOrderVO(List<Order>orderList,Integer userId){
        List<OrderVo> orderVoList=Lists.newArrayList();
        List<OrderItem> orderItemList=Lists.newArrayList();
        for(Order order:orderList){
            if(userId==null){
                 orderItemList = orderItemMapper.selectListOrderItem(null, order.getOrderNo());
            }else{
                 orderItemList = orderItemMapper.selectListOrderItem(userId, order.getOrderNo());
            }
            OrderVo orderVo = this.assembleOrderVO(order, orderItemList);
            orderVoList.add(orderVo);
        }
       return  orderVoList;
    }

    private BigDecimal getOrderTotalPrice(List<OrderItem> orderItemList){
        BigDecimal totalPrice=new BigDecimal("0");
        for(OrderItem orderItem:orderItemList){
            totalPrice=BigDecimalUtil.add(totalPrice.doubleValue(),orderItem.getTotalPrice().doubleValue());
        }
        return  totalPrice;
    }

    private Long generateOrderNo(){
        long currentTime = System.currentTimeMillis();
        return currentTime+new Random().nextInt(100);
    }

    private void addOrderItemOrderNo(List<OrderItem> orderItemList,Long orderNo){
        for(OrderItem orderItem:orderItemList){
            orderItem.setOrderNo(orderNo);
        }
    }

    private void reduceStock(List<OrderItem> orderItemList){
        for(OrderItem orderItem:orderItemList){
            Product product = productMapper.selectByPrimaryKey(orderItem.getProductId());
            int stock = product.getStock() - orderItem.getQuantity();
            product.setStock(stock);
            productMapper.updateByPrimaryKeySelective(product);
        }
    }

    private void clearShoppingCart(List<Cart> cartList){
      for(Cart cart:cartList){
          cartMapper.deleteByPrimaryKey(cart.getId());
      }
    }
                                               //内部通过order的属性查找orderItemList太麻烦，索性外部传入
    private OrderVo assembleOrderVO(Order order,List<OrderItem> orderItemList){
        OrderVo orderVo=new OrderVo();
         orderVo.setOrderNo(order.getOrderNo());
         orderVo.setPayment(order.getPayment());
         orderVo.setPaymentType(order.getPaymentType());
         orderVo.setPaymentTypeDesc(Const.PaymentTypeEnum.codeOf(order.getPaymentType()).getDes());
         orderVo.setPostage(order.getPostage());
         orderVo.setStatusDesc(Const.OrderStatusEnum.codeOf(order.getStatus()).getDes());
         orderVo.setCreatTime(DateTimeUtil.dateToStr(order.getCreateTime()));
         orderVo.setCloseTime(DateTimeUtil.dateToStr(order.getCloseTime()));
         orderVo.setEndTime(DateTimeUtil.dateToStr(order.getEndTime()));
         orderVo.setPaymentTime(DateTimeUtil.dateToStr(order.getPaymentTime()));
         orderVo.setSendTime(DateTimeUtil.dateToStr(order.getSendTime()));

        Integer shippingId = order.getShippingId();
        orderVo.setOrderItemList(orderItemList);
         orderVo.setShippingId(shippingId);
        Shipping shipping = shippingMapper.selectByPrimaryKey(shippingId);
        if(shipping !=null){
            orderVo.setShippingVO(this.assembleShippingVO(shipping));
            orderVo.setReceiverName(shipping.getReceiverName());
        }
        orderVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));

      return  orderVo;
    }


    private List<OrderItemVo>  assembleOrderItemVo(List<OrderItem> orderItemList){
        List<OrderItemVo>orderItemVoList=Lists.newArrayList();
        OrderItemVo orderItemVo=new OrderItemVo();
        for(OrderItem item:orderItemList){
            orderItemVo.setOrderNo(item.getOrderNo());
            orderItemVo.setProductName(item.getProductName());
            orderItemVo.setProductImage(item.getProductImage());
            orderItemVo.setCurrentUnitPrice(item.getCurrentUnitPrice());
            orderItemVo.setQuantity(item.getQuantity());
            orderItemVo.setTotalPrice(item.getTotalPrice());
            orderItemVo.setCreateTime(DateTimeUtil.dateToStr(item.getCreateTime()));
            orderItemVo.setUpdateTime(DateTimeUtil.dateToStr(item.getUpdateTime()));
            orderItemVoList.add(orderItemVo);
        }
          return orderItemVoList;

    }

    private ShippingVO assembleShippingVO(Shipping shipping){
        ShippingVO shippingVO=new ShippingVO();
        shippingVO.setReceiverAddress(shipping.getReceiverAddress());
        shippingVO.setReceiverCity(shipping.getReceiverCity());
        shippingVO.setReceiverDistrict(shipping.getReceiverDistrict());
        shippingVO.setReceiverMobile(shipping.getReceiverMobile());
        shippingVO.setReceiverPhone(shipping.getReceiverPhone());
        shippingVO.setReceiverProvince(shipping.getReceiverProvince());
        shippingVO.setReceiverZip(shipping.getReceiverZip());
        shippingVO.setReceiverName(shipping.getReceiverName());
        return  shippingVO;
    }

    private OrderProductVO assembleOrderProductVO(List<OrderItemVo> orderItemVoList){
        OrderProductVO orderProductVO=new OrderProductVO();
        orderProductVO.setOrderItemVoList(orderItemVoList);
        orderProductVO.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        BigDecimal totalPrice =new BigDecimal("0");
        for(OrderItemVo orderItemVo:orderItemVoList){
            totalPrice=BigDecimalUtil.add(totalPrice.doubleValue(),orderItemVo.getTotalPrice().doubleValue());
        }
        orderProductVO.setProductTotalPrice(totalPrice);
        return orderProductVO;
    }



    @Override
    public ResponseCode pay(Integer userId, Long orderId, String path) {
        Map resultMap= Maps.newHashMap();
        if(userId==null && orderId==null && path==null)
            return ResponseCode.createByErrorMessage("内部参数错误");
//        查询订单是否存在
        Order order = orderMapper.selectOrderByOrderIdUserId(orderId, userId);
        if(order==null)
            return ResponseCode.createByErrorMessage("查询订单错误");
        resultMap.put("orderNo",order.getOrderNo());

//      为支付宝扫码支付的必要对象属性赋值
           // (必填) 商户网站订单系统中唯一订单号，64个字符以内，只能包含字母、数字、下划线，
           // 需保证商户系统端不能重复，建议通过数据库sequence生成，
           String outTradeNo = order.getOrderNo().toString();

           // (必填) 订单标题，粗略描述用户的支付目的。如“xxx品牌xxx门店当面付扫码消费”
           String subject = new StringBuilder().append("happymmall扫码支付,订单号:").append(outTradeNo).toString();

           // (必填) 订单总金额，单位为元，不能超过1亿元
           // 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
           String totalAmount = order.getPayment().toString();

           // (可选) 订单不可打折金额，可以配合商家平台配置折扣活动，如果酒水不参与打折，则将对应金额填写至此字段
           // 如果该值未传入,但传入了【订单总金额】,【打折金额】,则该值默认为【订单总金额】-【打折金额】
           String undiscountableAmount = "0";

           // 卖家支付宝账号ID，用于支持一个签约账号下支持打款到不同的收款账号，(打款到sellerId对应的支付宝账号)
           // 如果该字段为空，则默认为与支付宝签约的商户的PID，也就是appid对应的PID
           String sellerId = "";

           // 订单描述，可以对交易或商品进行一个详细地描述，比如填写"购买商品2件共15.00元"
            String body = new StringBuilder().append("订单").append(outTradeNo).append("购买商品共").append(totalAmount).append("元").toString();

           // 商户操作员编号，添加此参数可以为商户操作员做销售统计
            String operatorId = "test_operator_id";

           // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
           String storeId = "test_store_id";

           // 业务扩展参数，目前可添加由支付宝分配的系统商编号(通过setSysServiceProviderId方法)，详情请咨询支付宝技术支持
           ExtendParams extendParams = new ExtendParams();
           extendParams.setSysServiceProviderId("2088100200300400500");

           // 支付超时，定义为120分钟
           String timeoutExpress = "120m";

           // 商品明细列表，需填写购买商品详细信息，
           List<GoodsDetail> goodsDetailList = new ArrayList<GoodsDetail>();
           List<OrderItem> orderItemList = orderItemMapper.selectListOrderItem(userId, orderId);
            for(OrderItem orderItem:orderItemList){
                GoodsDetail goodsDetail=GoodsDetail.newInstance(orderItem.getProductId().toString(),orderItem.getProductName(),
                    BigDecimalUtil.multiply(orderItem.getCurrentUnitPrice().doubleValue(),Double.valueOf(100)).longValue(),
                    orderItem.getQuantity());
              goodsDetailList.add(goodsDetail);
          }
//      设置相关参数，发起扫码请求
           // 创建扫码支付请求builder，设置请求参数
           AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder()
                .setSubject(subject).setTotalAmount(totalAmount).setOutTradeNo(outTradeNo)
                .setUndiscountableAmount(undiscountableAmount).setSellerId(sellerId).setBody(body)
                .setOperatorId(operatorId).setStoreId(storeId).setExtendParams(extendParams)
                .setTimeoutExpress(timeoutExpress)
                .setNotifyUrl(PropertiesUtil.getProperty("alipay.callback.url"))//支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
                .setGoodsDetailList(goodsDetailList);

//      返回成功状态，接收支付宝发回的付款二维码
            AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);
            switch (result.getTradeStatus()) {
                case SUCCESS:
                    logger.info("支付宝预下单成功: )");
                    AlipayTradePrecreateResponse response = result.getResponse();
                    dumpResponse(response);

//      将二维码暂存在本地
                    File folder=new File(path);
                    if(!folder.exists()){
                        folder.setWritable(true);
                        folder.mkdir();
                    }
                    //为二维码文件重命名，本地暂存路径（注意加/）
                    String qrPath = String.format(path+"/qr-%s.png",response.getOutTradeNo());
                    //为二维码文件重命名，ftp服务器路径
                    String qrFileName = String.format("qr-%s.png",response.getOutTradeNo());
                    ZxingUtils.getQRCodeImge(response.getQrCode(), 256, qrPath);
   //      将二维码上传到ftp
                    File targetPath=new File(path,qrFileName);
                    try {
                        FTPUtils.upload(Lists.newArrayList(targetPath));
                    } catch (IOException e) {
                       logger.error("上传服务器错误"+e);
                    }
//          拼接二维码的访问地址发给页面
              String url=PropertiesUtil.getProperty("ftp.server.http.prefix")+targetPath.getName();
               resultMap.put("url",url);
                    return ResponseCode.creatBySuccess(resultMap);

                case FAILED:
                    logger.error("支付宝预下单失败!!!");
                    return ResponseCode.createByErrorMessage("支付宝预下单失败!!!");

                case UNKNOWN:
                    logger.error("系统异常，预下单状态未知!!!");
                    return ResponseCode.createByErrorMessage("系统异常，预下单状态未知!!!");

                default:
                    logger.error("不支持的交易状态，交易返回异常!!!");
                    return ResponseCode.createByErrorMessage("不支持的交易状态，交易返回异常!!!");
            }

        }

        @Override
        public ResponseCode alipayCallBack(Map<String,String> paramMap){
         //获取订单号，交易号，交易状态
           Long orderNo=Long.parseLong(paramMap.get("out_trade_no"));
           String tradeNo=paramMap.get("trade_no");
           String tradeStatus=paramMap.get("trade_status");
           String paymentTime = paramMap.get("gmt_payment");
            //根据回调的订单号查询数据库是否合法
            Order order = orderMapper.selectOrderByOrderIdUserId(orderNo, null);
            if(order==null){
                return ResponseCode.createByErrorMessage("回调订单号错误");
            }
            //根据回调的订单状态与数据库中的订单状态进行比较看是否为重复通知
            if(order.getStatus()>=Const.OrderStatusEnum.PAYED.getCode()){
                return ResponseCode.creatBySuccess("支付宝通知重复");
            }
           //在回调状态是SUCCESS的情况下获取回调的相关参数保存在数据库中
            if(Const.AliPayCallBackStatus.RESPONSE_SUCCESS.equals(tradeStatus)){
                order.setStatus(Integer.parseInt(tradeStatus));
                order.setPaymentTime(DateTimeUtil.strToDate(paymentTime));
                int resultCount = orderMapper.updateByPrimaryKeySelective(order);
                if(resultCount==0){
                    return ResponseCode.createByErrorMessage("修改订单状态错误");
                }
            }

            PayInfo payInfo=new PayInfo();
            payInfo.setOrderNo(orderNo);
            payInfo.setPayPlatform(Const.PayPlatformEnum.ALIPAY.getCode());
            payInfo.setPlatformNumber(tradeNo);
            payInfo.setUserId(order.getUserId());
            payInfo.setPlatformStatus(tradeStatus);
            int resultCount = payInfoMapper.insert(payInfo);
            if(resultCount==0)
                  return ResponseCode.createByErrorMessage("添加支付信息错误");
            return ResponseCode.creatBySuccess("添加成功");
        }

        @Override
        public ResponseCode<Boolean> queryOrderStatus(Integer userId,Long orderId){
        if(userId==null && orderId==null)
            return ResponseCode.createByErrorMessage("参数错误");

            Order order = orderMapper.selectOrderByOrderIdUserId(orderId, userId);
            if(order==null)
                return ResponseCode.createByErrorMessage("订单不存在");

            if(order.getStatus()>=Const.OrderStatusEnum.PAYED.getCode())
                return ResponseCode.creatBySuccess("校验成功");
            return ResponseCode.createByError();
        }


    // 简单打印应答
    private void dumpResponse(AlipayResponse response) {
        if (response != null) {
            logger.info(String.format("code:%s, msg:%s", response.getCode(), response.getMsg()));
            if (StringUtils.isNotEmpty(response.getSubCode())) {
                logger.info(String.format("subCode:%s, subMsg:%s", response.getSubCode(),
                        response.getSubMsg()));
            }
            logger.info("body:" + response.getBody());
        }
    }


}
